""" 登录接口 封装"""
import re

import requests
import yaml
from jsonpath import jsonpath

from common.requesthandler import HttpHandler
from common.sqlhandler import DBHandler
from config.setting import config
from midware.ymlhandler import yamlhandler
yamal_data = yamlhandler(config.yaml_path).open_yaml()

class Context:
    # tpken = '2316dfg46d8f4vd35f1v6'
    # menber_id = None
    # loan_id = None
    # prototy  把方法转为属性，类.方法即可调用
    @property
    def loan_id(self):
        db = DBHandler(host=yamal_data['DBdatabase']['host'],
                            port=yamal_data['DBdatabase']['port'],
                            user=yamal_data['DBdatabase']['user'],
                            password=yamal_data['DBdatabase']['password'],
                            charset=yamal_data['DBdatabase']['charset'],
                            database=yamal_data['DBdatabase']['database'])
        res = db.query("SELECT * FROM menber WHERE status = 2;")
        db.dbclose()
        # print(res)
        return res['id']

    @property
    def token(self):
        """token  token会动态变化，只需要Context（）.token就能获取
                调用login，获取最新token
        """
        data = login_token()
        # token = jsonpath(data,'$..token')[0]
        # 不要命名为token，上面方法名重名
        t = jsonpath(data,'$..token')
        return t

    @property
    def member_id(self):
        data = login_token()
        id = jsonpath(data, '$..menber_id')
        return id


def login_token():
    req = HttpHandler()
    data = yamlhandler(config.yaml_path).open_yaml()
    res = req.visit('post', 'http://test.lemonban.com/futureloan/mvc/api/member/login', data=data['user'])
    return res


def save_token():
    res = login_token()
    from jsonpath import jsonpath
    # 返回一个数组
    token = jsonpath(res, '$..token')
    token_type = jsonpath(res, '$..token_type')
    menber_id = jsonpath(res, '$..menber_id')

    # todo 存储到类里面，可以随时调用，有多少变量都不是问题
    Context.token = token
    Context.menber_id = menber_id

    return {'token': token, 'menber_id': menber_id}


# 封装，匹配出来后能够替换
def replce_able(excelstr):
    """while 循环 ，每次替换一个    re.search 每次只能找到一个"""
    re_pattern = r'#(.*?)#'
    while re.findall(re_pattern, excelstr):
        # print(re.findall(re_pattern,excelstr))
        # 第一次查到有2个，替换一个；第二次 剩1个，替换；第三次退出
        # 组  re.search(reg,sr) =><re.Match object; span=(16, 29), match='#mobilephone#'>
        #  .group(1)   得到mobilephone
        key = re.search(re_pattern, excelstr).group(1)
        print(key, 'key')
        # 替换   Context中添加好要替换的变量即可
        excelstr = re.sub(re_pattern, str(getattr(Context, key)), excelstr, 1)
    return excelstr


if __name__ == '__main__':
    # res = save_token()
    print(Context().loan_id)

    """
    token 实在返回的响应体里面，可能有比较多的对象覆盖，可以用jsonpath，安装
    """
    # from jsonpath import jsonpath
    # print(jsonpath(res,'$..token'))   # $.. 不管有多少层都能查找出来，有多个就会用列表存储
